package com.hdrx.fundhelper.utils;

import cn.hutool.poi.word.DocUtil;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Objects;


/**
 * @author: houdx
 * @description: word 转 PDF
 * @date: 2023/8/9 16:17
 */
@Slf4j
public class Word2Pdf {


    /**
     * word 转 Pdf
     * @param wordFilePath word 文件路径
     */
    public static void word2Pdf(String wordFilePath) {

        //生成的 pdf 文件路径
        String pdfFilePath = getPdfFilePath(wordFilePath);

        File file = new File(pdfFilePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        getLicense();
        try {
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(wordFilePath);
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf失败", e);
            e.printStackTrace();
        }
    }

    /**
     * 获取 生成的 pdf 文件路径，默认与源文件同一目录
     *
     * @param wordFilePath word文件路径
     * @return 生成的 pdf 文件
     */
    private static String getPdfFilePath(String wordFilePath) {
        String[] split = wordFilePath.split("\\.");
        return split[0] + ".pdf";
    }

    /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    private static void getLicense() {
        String licenseFilePath = "word-license.xml";
        try {
            InputStream is = DocUtil.class.getClassLoader().getResourceAsStream(licenseFilePath);
            License license = new License();
            license.setLicense(Objects.requireNonNull(is));
        } catch (Exception e) {
            log.error("license verify failed");
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String docFilePath = "D:/test/1234.doc";
        word2Pdf(docFilePath);
    }
}
